        // 映射表，将天气类型映射到图标 URL，要求图标文件夹与当前页面同级！！！
        const weatherBackgrounds = {
            "晴": "./black/0@2x.png",  
            "多云": "./black/4@2x.png",  
            "晴间多云": "./black/5@2x.png",  
            "大部多云": "./black/7@2x.png",  
            "阴": "./black/9@2x.png",  
            "阵雨": "./black/10@2x.png",  
            "雷阵雨": "./black/11@2x.png",  
            "雷阵雨伴有冰雹": "./black/12@2x.png",  
            "小雨": "./black/13@2x.png",  
            "中雨": "./black/14@2x.png",  
            "大雨": "./black/15@2x.png",  
            "暴雨": "./black/16@2x.png",  
            "大暴雨": "./black/17@2x.png",  
            "特大暴雨": "./black/18@2x.png",  
            "冻雨": "./black/19@2x.png",  
            "雨夹雪": "./black/20@2x.png",  
            "阵雪": "./black/21@2x.png",  
            "小雪": "./black/22@2x.png",  
            "中雪": "./black/23@2x.png",  
            "大雪": "./black/24@2x.png",  
            "暴雪": "./black/25@2x.png",  
            "浮尘": "./black/26@2x.png",  
            "扬沙": "./black/27@2x.png",  
            "沙尘暴": "./black/28@2x.png",  
            "强沙尘暴": "./black/29@2x.png",  
            "雾": "./black/30@2x.png",  
            "霾": "./black/31@2x.png",  
            "风": "./black/32@2x.png",  
            "大风": "./black/33@2x.png",  
            "飓风": "./black/34@2x.png",  
            "热带风暴": "./black/35@2x.png",  
            "龙卷风": "./black/36@2x.png",  
            "冷": "./black/37@2x.png",  
            "热": "./black/38@2x.png",  
            "未知": "./black/99@2x.png"
        };
		
        //获取天气数据并更新数据
		function fetchWeatherData(cityId) {
			const xhr = new XMLHttpRequest();
			const url = `https://widget-v3.seniverse.com/api/weather/your_token?unit=c&language=zh-Hans&location=${cityId}&geolocation=false&detected=zh-cn`;
			console.log(url);
			xhr.onreadystatechange = function () {
				if (xhr.readyState === 4 && xhr.status === 200) {
					const data = JSON.parse(xhr.responseText);
					// 获取主要数据
					const mainData = data.results[0].data[0];
					// 更新城市名称
					document.querySelector('h1').innerText = mainData.location + ' 天气';
					// 更新天气状况
					const tempElement = document.querySelector('.temp');
					tempElement.innerHTML = mainData.text + '&nbsp;&nbsp;' + mainData.temperature + 'C';
					// 更新温度范围
					document.querySelector('.range').innerHTML = '<i class="fa-solid fa-temperature-high" id="i_temperature"></i>&nbsp;' + mainData.today.low + ' - ' + mainData.today.high;
					
					// 计算温差
					const temperatureRange = parseInt(mainData.today.high.replace('°C', '')) - parseInt(mainData.today.low.replace('°C', ''));
					// 更新穿衣建议
					const clothingAdvice = getClothingAdvice(mainData.today.low, mainData.today.high, temperatureRange);
					document.querySelector('.clothing').innerHTML = '<i class="fa-solid fa-shirt"></i>&nbsp;&nbsp;<i class="fa-solid fa-hashtag"></i>' + clothingAdvice;

					// 检查地质灾害告警信息
					let alertMessage = '';
					if (mainData.alarms && mainData.alarms.length > 0) {
						const firstAlarm = mainData.alarms[0];
						const alarmDate = new Date(firstAlarm.pubDate);

						// 检查时间是否在36小时内
						if (isWithin36Hours(alarmDate)) {
							alertMessage = firstAlarm.description;
							document.getElementById('alert').innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i>&nbsp;&nbsp;&nbsp;' + alertMessage;
							document.getElementById('alert').style.display = 'block';
							document.getElementById('noAlert').style.display = 'none';
							// 根据警报级别设置颜色
							updateAlertColor(firstAlarm.level);
						} else {
							// 如果不在36小时内，不显示告警
							document.getElementById('alert').style.display = 'none';
						}
					} else {
						// 如果没有告警信息
						document.getElementById('noAlert').innerHTML = '<i class="fa-solid fa-shield-dog"></i>&nbsp;&nbsp;&nbsp;' + '气象站的小狗说：“目前天气棒棒哒，没有告警打扰。”';
						document.getElementById('alert').style.display = 'none';
						document.getElementById('noAlert').style.display = 'block';
					}

					// 根据天气类型设置天气图标
					setWeatherIcon(mainData.text);
				} else if (xhr.readyState === 4) {
					console.error('请求失败');
				}
			};
			xhr.open('GET', url, true);
			xhr.send();
		}

		// 检查时间是否在36小时内
		function isWithin36Hours(timestamp) {
			const now = Date.now(); // 当前时间戳
			const thirtySixHoursAgo = now - (36 * 60 * 60 * 1000); // 36小时前的时间戳
			return timestamp.getTime() >= thirtySixHoursAgo;
		}
        
        
        
        // 根据警报级别设置告警字体颜色
        function updateAlertColor(level) {
            const levelColors = {
                '蓝色': '#0099ff',
                '黄色': '#ffcc00',
                '橙色': '#ff9900',
                '红色': '#ff0000',
                '白色': '#ffffff'
            };
            const color = levelColors[level.toLowerCase()];
            if (color) {
                document.querySelector('.weather-widget .alert').style.color = color;
            }
        }
        
        
        // 提供穿衣建议
        function getClothingAdvice(lowTemp, highTemp, temperatureRange) {
            const low = parseInt(lowTemp.replace('°C', ''));
            const high = parseInt(highTemp.replace('°C', ''));
            
            let advice = '';
            if (low >= 25) {
                advice = '天气热，建议着短裙、短裤、短薄外套、T恤等夏季服装。';
            } else if (low >= 20) {
                advice = '天气较热，建议着短袖衬衫、短裤或短裙等夏季服装。';
            } else if (low >= 15) {
                advice = '气温适中，建议着长袖衬衫、长裤等春秋装。';
            } else if (low >= 10) {
                advice = '气温较低，建议着长袖上衣、长裤，并携带一件薄外套。';
            } else {
                advice = '天气冷，建议着厚外套、毛衣等保暖衣物。';
            }
            
            // 如果温差大于等于10度，增加提示
            if (temperatureRange >= 10) {
                advice += ' 温差较大，请适当增减衣物以防感冒。';
            }
            
            return advice;
        }
        
        
    //右上角小图标    
        function setWeatherIcon(weatherType) {
            // 使用默认图片作为回退选项
            const defaultImage = "./black/99@1x.png";
            // 从映射表中获取图片 URL
            const imageUrl = weatherBackgrounds[weatherType] || defaultImage;
            // 设置图片源
            document.getElementById('weather-icon').src = imageUrl;
            document.getElementById('weather-icon').style.display = 'block';
        }
        
  
	
	//获取用户的IP并使用高级IP库来重新定位，虽然没必要，但还是拓宽了技术层面
		function fetchIPAddress() {
					const xhr = new XMLHttpRequest();
					const ipUrl = 'https://api.vvhan.com/api/ipInfo';//前人栽树后人乘凉
					xhr.onreadystatechange = function () {
						if (xhr.readyState === 4 && xhr.status === 200) {
							const data = JSON.parse(xhr.responseText);
							const ipAddress = data.ip;
							fetchIPDetails(ipAddress);
						} else if (xhr.readyState === 4) {
							console.error('请求失败');
						}
					};
					xhr.open('GET', ipUrl, true);
					xhr.send();
				}
				//向后端服务器发送请求
				function fetchCityIdFromServer(city) {
                    const xhr = new XMLHttpRequest();
                    const serverUrl = `https://example.com/match-city?city=${city}`;//对应后端server.js
                    console.log(serverUrl);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                            console.log('Request complete');
                            if (xhr.status === 200) {
                                console.log('Response received:', xhr.responseText);
                                const cityId = JSON.parse(xhr.responseText).city_id;
                                console.log(cityId);
                                // 调用 fetchWeatherData 函数并将城市ID传递进去
                                fetchWeatherData(cityId);
                            } else {
                                console.error('请求失败, status:', xhr.status);
                            }
                        }
                    };
                
                    xhr.open('GET', serverUrl, true);
                    //console.log('Opening request:', serverUrl);
                    try {
                        xhr.send();
                        console.log('Request sent');
                    } catch (error) {
                        console.error('Error sending request:', error);
                    }
                }
				//高级定位
				function fetchIPDetails(ipAddress) {
					const xhr = new XMLHttpRequest();
					const detailsUrl = `https://cz88.net/api/cz88/ip/openIPInfo?ip=${ipAddress}`;//前人栽树后人乘凉
					console.log(detailsUrl);
					xhr.onreadystatechange = function () {
						if (xhr.readyState === 4 && xhr.status === 200) {
							const data = JSON.parse(xhr.responseText);
							const ipDetails = data.data;

							document.getElementById('ip-address').innerHTML = `<i class="fa-duotone fa-solid fa-location-dot" id="i_ip"></i>&nbsp;&nbsp;您当前IP地址: ${ipDetails.ip}`;
							const city = extractCityFromGeo(ipDetails.geo);
							document.getElementById('ip-city').innerHTML = `<i class="fa-solid fa-globe"></i>&nbsp; 您所在城市: ${city}`;
							// 发送城市名到后端服务器进行模糊匹配
							fetchCityIdFromServer(city);
						} else if (xhr.readyState === 4) {
							console.error('请求失败');
						}
					};
					xhr.open('GET', detailsUrl, true);
					xhr.send();
				}
				
				
				// function extractCityFromGeo(geoString) {
    //                 // 正则表达式匹配地级市的部分
    //                 const regex = /–[^–]+–([^–]+)(?:–[^–]+)?$/;
    //                 const match = geoString.match(regex);
    //                 if (match && match[1]) {
    //                     return match[1]; // 返回匹配的地级市名称
    //                 }
    //                 return '未知';
    //             }
				
				
				
				function extractCityFromGeo(geoString) {
					// 匹配地级市或区县的部分
					const regex = /–[^–]+–([^–]+)(?:–([^–]+))?$/;
					const match = geoString.match(regex);
				
					if (match) {
						let result;
						// 如果存在区县信息，则处理区县名称
						if (match[2]) {
							result = match[2];
						}
						// 否则处理地级市名称
						else {
							result = match[1];
						}
				
						// 去除“区”、“县”或“市”
						return result.replace(/区|县|市$/, '');
					}
					return '未知';
				}
				
	
	        // 在页面加载完成后执行函数
	        window.onload = function () {
	            fetchIPAddress();
				fetchWeatherData();
	        };